#!/usr/bin/python
#coding=UTF-8
#--------------------------
#Created by PyCharm
#Author: Kingson
#Date: 12-8-23
#Time: 下午9:19
#Description: A simple books management systems for TNS.
#--------------------------
from bottle import *
from creatdb import *
import time

@get('/')
@get('/login')
def login_forms():
    return template('login_forms')

@post('/login')
def login_submit():
    check_db()
    username = request.forms.get('username','').strip()
    password = request.forms.get('password','').strip()
    if username and password :
        conn = sqlite3.connect('data/books.db')
        conn.text_factory = str
        c = conn.cursor()
        c.execute("select account,password from users where account = ? and password = ?",(username,password))
        cur_data = c.fetchone()
        if cur_data:
            if username == cur_data[0] and password == cur_data[1]:
                return '''<meta http-equiv="refresh" content="3;url=/userlist"><p>login success</p>'''
            else:
                return "<p>login failed</p>"
        else:
            return "<p>username or password is incorrect"
    else:
        return "<p>username or password is null</p>"
@get('/singin')
def singin_forms():
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return template('singin_forms',logintime = datetime )

@post('/singin')
def singin_submit():
    username = request.forms.get('username')
    password = request.forms.get('password')
    nickname = request.forms.get('nickname')
    email = request.forms.get('email')
    department = request.forms.get('department')
    jobnumber = request.forms.get('jobnumber')
    onjob = request.forms.get('onjob')
    logintime = request.forms.get('logintime')
    description = request.forms.get('description')
    if onjob == 'on':
        onjob = 1
    else:
        onjob = 0
    if username and password and nickname and email:
        conn = sqlite3.connect('data/books.db')
        conn.text_factory = str
        c = conn.cursor()
        c.execute(
            "INSERT INTO users (account,password,nickname,email,department,jobnumber,onjob,logintime,description) VALUES "
            "(?,?,?,?,?,?,?,?,?)",(username,password,nickname,email,department,jobnumber,onjob,logintime,description))
        conn.commit()
        c.close()
        return '''<meta http-equiv="refresh" content="3;url=/userlist"><p>register success</p>'''
    else:
        return "<p>register failed</p>"

@get('/userlist')
def show_userlist():
    conn = sqlite3.connect('data/books.db')
    c = conn.cursor()
    c.execute("select * from users")
    result = c.fetchall()
    result_list = list(result)
    c.close()
    output = template('show_userlist', rows=result_list)
    return output

debug(mode=True)
run(port=1024,reloader=True)
